<template>
	<div
		:class="[
			'app-editor-container',
			'app-span',
			`app-span-${name}`,
			[textClass],
		]"
	>
		<span :title="getFormatDate()" v-if="DataTypeUtil.isDate(dataTypeValue)">{{
			getFormatDate()
		}}</span>
		<span
			v-else-if="textFormat"
			:title="getFormatDate()"
			v-html="getFormatData()"
		></span>
		<div
			v-else-if="
				editorType == 'PICTURE' ||
				editorType == 'PICTURE_ONE' ||
				editorType == 'FILEUPLOADER'
			"
		>
			<a
				v-for="file in fileList"
				@click.stop.prevent="onDownload(file)"
				:key="file"
				>{{ file.name }}</a
			>
		</div>
		<span v-else :title="text">{{ text }}{{ unitName }}</span>
	</div>
</template>

<script setup lang="ts">
import { spanProps } from './span';
import {
	isExistAndNotEmpty,
	DataTypeUtil,
	deepCopy,
	IParam,
	format,
	isEmpty,
} from '@/core';
import {
	handleEditorNavParams,
	getDownloadUrl,
	useEditorTypeParams,
} from '@/hooks/use-editor';
import { format as formatFns, parseISO } from 'date-fns';
import { Http } from '@/http/http';
const props = defineProps(spanProps);
// 类型校验
const {
	validateConfig,
	valueType,
	valueSeparator,
	objectNameField,
	objectIdField,
	objectValueField,
	textSeparator,
} = useEditorTypeParams();
validateConfig();
//  数据类型
const dataTypeValue = computed(() => {
	return DataTypeUtil.toString(props.dataType);
});
let text = ref<string>('');
let textClass = ref<string>('');
let textFormat = ref<string>('');
const fileList = ref<any[]>([]);
const downloadUrl = getDownloadUrl(); //文件下载基础路径
//  初始化值
const initText = async () => {
	if (props.codeListTag) {
		const { navContext, navViewParam } = handleEditorNavParams(props);
		const result = await App.getAppCodeListHelper().getCodeListItems(
			props.codeListTag,
			navContext,
			navViewParam
		);
		if (result.ok) {
			const item: IParam | undefined = result.data.find((item: any) => {
				return item.value == props.value;
			});
			if (item) {
				text.value = item.text;
				textClass.value = item.textClass;
			} else {
				text.value = props.value as string;
			}
		}
	} else if (
		props.editorType == 'PICTURE' ||
		props.editorType == 'PICTURE_ONE' ||
		props.editorType == 'FILEUPLOADER'
	) {
		if (props.value && typeof props.value == 'object') {
			fileList.value = props.value.fileList;
			if (fileList.value && fileList.value.length > 0) {
				fileList.value.forEach((file: any) => {
					let url = `${downloadUrl}/${file.response.id}`;
					file.url = url;
				});
			}
		}
	} else if (
		!props.value &&
		props.value !== 0 &&
		!props.unitName &&
		Object.is('STYLE1', props.noValueShowMode)
	) {
		text.value = '---';
	} else {
		handleValueType();
	}
	if (props.valueFormat) {
		textFormat.value = props.valueFormat;
	} else if (DataTypeUtil.isDate(dataTypeValue.value)) {
		textFormat.value = 'yyyy-MM-dd HH:mm:ss';
	}
};
// 处理不同值类型的参数
const handleValueType = () => {
	let value: any;
	let item: any = deepCopy(props.value as any);
	if (item) {
		if (valueType == 'SIMPLES') {
			text.value = item.join(
				textSeparator ? textSeparator : valueSeparator ? valueSeparator : ','
			);
		} else if (valueType == 'OBJECT') {
			text.value = objectNameField
				? item[objectNameField]
				: item[props.deMajorField];
		} else if (valueType == 'OBJECTS') {
			value = [];
			const items: any[] = item;
			items.forEach((_item: any) => {
				value.push(
					objectNameField ? _item[objectNameField] : _item[props.deMajorField]
				);
			});
			text.value = value.join(
				textSeparator ? textSeparator : valueSeparator ? valueSeparator : ','
			);
		} else {
			// 解析地址选择器的JSON字符串数据
			if (props.editorType === 'ADDRESSPICKUP') {
				value = [];
				const items: any[] = JSON.parse(item);
				items.forEach((_item: any) => {
					value.push(
						objectNameField ? _item[objectNameField] : _item[props.deMajorField]
					);
				});
				text.value = value.join(
					textSeparator ? textSeparator : valueSeparator ? valueSeparator : ','
				);
			} else {
				text.value = item as string;
			}
		}
	}
};
//  获取格式化数据
const getFormatData = () => {
	if (!isExistAndNotEmpty(`${props.value}`)) {
		return '';
	}
	let value: any = props.value;
	try {
		if (DataTypeUtil.isNumber(dataTypeValue.value)) {
			let number: any = Number(value);
			const decimalCnt: number =
				value?.toString()?.split('.').length > 1
					? value.toString().split('.')[1].length
					: 0;
			value =
				props.precision === 0 && decimalCnt !== 0
					? number.toFixed(decimalCnt)
					: number.toFixed(props.precision);
		}
		value = format.format(value, textFormat.value);
	} catch (error) {
		console.error(error);
	}
	return value;
};

//  获取格式化日期
const getFormatDate = (): string => {
	if (!isExistAndNotEmpty(`${props.value}`)) {
		return '';
	}
	if (props.value && typeof props.value === 'string') {
		try {
			const tempFormat = textFormat.value
				.replaceAll('Y', 'y')
				.replaceAll('D', 'd');
			const value = formatFns(parseISO(props.value), tempFormat);
			if (value) {
				return value;
			}
		} catch (error) {
			return props.value;
		}
	}
	return props.value as string;
};

onBeforeMount(() => {
	//  监听值变化
	watch(
		() => props.value,
		(newVal: any, oldVal: any) => {
			if (newVal !== oldVal) initText();
		},
		{ immediate: true }
	);
});

const onDownload = (file: any) => {
	//下载文件
	DownloadFile(file.url, file);
};

//下载文件
const DownloadFile = (url: string, file: any) => {
	// 发送get请求
	const downloaderror = App.ts('common.fileupload.downloaderror', '下载失败');
	Http.getHttp()({
		method: App.getProjectSetting().appRequestMode,
		url: url,
		responseType: 'blob',
	})
		.then((response: any) => {
			if (!response || response.status != 200) {
				App.getNotificationHelper().warning(downloaderror, '');
				return;
			}
			// 请求成功，后台返回的是一个文件流
			if (response.data) {
				// 获取文件名
				const filename = file.name;
				const ext = '.' + filename.split('.').pop();
				let filetype = calcFilemime(ext);
				// 用blob对象获取文件流
				let blob = new Blob([response.data], { type: filetype });
				// 通过文件流创建下载链接
				var href = URL.createObjectURL(blob);
				// 创建一个a元素并设置相关属性
				let a = document.createElement('a');
				a.href = href;
				a.download = filename;
				// 添加a元素到当前网页
				document.body.appendChild(a);
				// 触发a元素的点击事件，实现下载
				a.click();
				// 从当前网页移除a元素
				document.body.removeChild(a);
				// 释放blob对象
				URL.revokeObjectURL(href);
			} else {
				App.getNotificationHelper().warning(downloaderror, '');
			}
		})
		.catch((error: any) => {
			App.getNotificationHelper().warning(downloaderror, error);
		});
};
//计算文件类型
const calcFilemime = (filetype: string): string => {
	let mime = 'image/png';
	switch (filetype) {
		case '.wps':
			mime = 'application/kswps';
			break;
		case '.doc':
			mime = 'application/msword';
			break;
		case '.docx':
			mime =
				'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
			break;
		case '.txt':
			mime = 'text/plain';
			break;
		case '.zip':
			mime = 'application/zip';
			break;
		case '.png':
			mime = 'imgage/png';
			break;
		case '.gif':
			mime = 'image/gif';
			break;
		case '.jpeg':
			mime = 'image/jpeg';
			break;
		case '.jpg':
			mime = 'image/jpeg';
			break;
		case '.rtf':
			mime = 'application/rtf';
			break;
		case '.avi':
			mime = 'video/x-msvideo';
			break;
		case '.gz':
			mime = 'application/x-gzip';
			break;
		case '.tar':
			mime = 'application/x-tar';
			break;
	}
	return mime;
};
</script>
